var environment=_gl.environment||"production";
var ajaxUrl={
    "local":{
        "settimeoutTime":1400,
        "queryCourse":_gl._host_res+"/res/js/data/queryCourse.json?id=",
        "addCourse":_gl._host_res+"/res/js/data/addCourse.json",
        "updateCourse":_gl._host_res+"/res/js/data/updateCourse.json",
        "delCourse":_gl._host_res+"/res/js/data/delCourse.json",

        "addChapter":_gl._host_res+"/res/js/data/addChapter.json",
        "updateChapter":_gl._host_res+"/res/js/data/updateChapter.json",
        "delChapter":_gl._host_res+"/res/js/data/delChapter.json"
    },
    "production":{
        "settimeoutTime":0,
        "queryCourse":_gl._host_api+"/courses/",
        "addCourse":_gl._host_api+"/courses",
        "updateCourse":_gl._host_api+"/courses/",
        "delCourse":_gl._host_api+"/courses/",

        "queryChapter":_gl._host_api+"/chapters",
        "addChapter":_gl._host_api+"/chapters",
        "updateChapter":_gl._host_api+"/chapters/",
        "delChapter":_gl._host_api+"/chapters/"
    }
};

var _errorTips={
    "P001":"课程名称不能为空",
    "P002":"开课时间不能为空",
    "P003":"课程描述不能为空",
    "P004":"请选择课程封面",
    "P005":"章节名称不能为空",
    "P006":"章节内容不能为空",
    "P007":"正在提交数据，请稍后...",
    "P008":"正在加载课程内容，请稍后...",
    "P009":"章节视频不能为空",
    "P010":"章节音频不能为空",
    "P011":"章节图片不能为空"
};

$(function(){
    //console.log(_gl._request["flag"]);

    var _pageFlag = _gl._request["flag"];   //页面状态 新增add  修改update  查看query
    var _courseId = _gl._request["id"];     //课程id
    var _currentChapterId = "";
    var _courseData = {};                     //课程对象
    var _currentChapterIndex =0;              //当前查看课程里面的章节序号
    var _buttonFunInitIndex = null;
    var _loadingIndex = null;

    if(_pageFlag=="update" || _pageFlag=="query"){
        loadCourse();
    }else{
        btnInit();
    }
    //初始化上传文件
    $("input[type='file']").each(function(){
        $(this).UploadControl({"callback":function(){
            if($(this).attr("name") == "cover_id"){
                JudgmentNull($(this),"");
            }
        }});
    });

    var _status = getStatus();


    //DOM事件
    //所有输入框失去焦点事件
    $(document).on("blur","input,textarea",function(e){
        e.stopPropagation();
        var $this = $(this);
        var thisName = $this.attr("name");
        var tips ="";
        if(thisName=="course_time"){
            tips = _errorTips["P002"];
        }else if(thisName=="description"){
            tips = _errorTips["P003"];
        }else if(thisName=="cover_id"){
            tips = _errorTips["P004"];
        }else if(thisName=="content"){
            tips = _errorTips["P006"];
        }else if(thisName=="title"){
            var thisFormId = $this.parents("form").attr("id");
            if(thisFormId=="detailForm"){
                tips = _errorTips["P001"];
            }else{
                tips = _errorTips["P005"];
            }
        }
        if(tips){
            JudgmentNull($(this),tips);
        }
    });

    //点击多媒体播放或暂停
    $(document).on("click",'video',function(e){
        e.stopPropagation();
        var Media = document.getElementById($(this).attr("id"));
        if(Media){
            if(!Media.paused){
                Media.pause();
            }else{
                Media.play();
            }
        }
    });

    $(document).on( 'click','a,button,.glyphicon', function (e) {
        e.stopPropagation();
        if($(this).hasClass("btn-add-chapter")){
            //新增章节
            setModal({"flag":"add"});

        }else if($(this).hasClass("btn-edit-chapter")){
            //修改章节
            setModal({"flag":"update","chapterInfo":getChapterInfo($(this))});

        }else if($(this).hasClass("btn-query-chapter")){
            //查看章节
            setModal({"flag":"query","chapterInfo":getChapterInfo($(this))});

        }else if($(this).hasClass("btn-del-chapter")){
            //删除章节
            var chapterInfo=getChapterInfo($(this));
            delCourseOrChapter({"type":"chapter","id":chapterInfo.id});

        }else if($(this).hasClass("btn-add-chapter")){
            //新增章节
            setModal({"flag":"add"});

        }else if($(this).hasClass("btn-add-chapter-modal")){
            //模态框里面的新增或者修改章节
            submitChapterInfo({"flag":$(this).hasClass("update")?"update":"add"});

        }else {
        }
    });

    //模态框隐藏事件
    $('#myModal').on('hidden.bs.modal', function (e) {
        btnInit();
        setChapterForm();
        pauseVideo();
    });
    //模态框显示事件
    $('#myModal').on('show.bs.modal', function (e) {
        layer.closeAll();
        pauseVideo();
    });
    //章节内容改变
    $("select[name='chaptertype']").on("change",function(e){
        e.stopPropagation();
        if($(this).val()=="video"){
            $(".chapter_audio").hide();
            $(".chapter_video").show();
        }else{
            $(".chapter_audio").show();
            $(".chapter_video").hide();
        }
        $(".chapter_audio,.chapter_video").find("input").each(function(){
            $(this).UploadControl({"event":"showInput"});
        });
    });



    //初始化右上角按钮组
    function btnInit(){
        if(!_pageFlag || _pageFlag=="add"){
            _buttonFunInitIndex = _helper.buttonFunInit({"arr":[{"text":"新增","class":"add","callback":addItem}],"index":_buttonFunInitIndex});
        }else if(_pageFlag=="update"){
            _buttonFunInitIndex = _helper.buttonFunInit({"arr":[{"text":"修改","class":"update","callback":updateItem}],"index":_buttonFunInitIndex});
        }else if(_pageFlag=="query"){
            _buttonFunInitIndex = _helper.buttonFunInit({"arr":[{"text":"下架","class":"update-down","callback":updateDownItem}],"index":_buttonFunInitIndex});
        }
        setInputReadOnly();
    }
    //设置表单是否可修改
    function setInputReadOnly(){
        $("#detailForm").find("input,textarea").each(function(){
            var $this = $(this);
            if(_status){
                $this.attr("readonly","readonly");
                if($this.attr("type")=="file"){
                    $this.prop("disabled",true);
                }
                $(".btn-change-pic").hide();
                $(".btn-change-video").hide();

                //移除日期控件
                $('#course_time').datetimepicker('remove');
            }else{
                $this.removeAttr("readonly");
                if($this.attr("type")=="file"){
                    $this.prop("disabled",false);
                }
                $(".btn-change-pic").show();
                $(".btn-change-video").show();
                //日期初始化
                $('#course_time').datetimepicker({
                    format: 'yyyy-mm-dd',
                    autoclose:true,
                    minView: 'month',
                    todayBtn:true,
                    language:"zh-CN",
                    startDate:_helper.getCurrentDate(),
                    todayHighlight:false
                }).on("hide",function(){
                    var $this = $(this);
                    JudgmentNull($this,_errorTips["P002"]);
                });
            }
        });
        $("#chapterForm").find("input,textarea").each(function(){
            var $this = $(this);
            if(_status){
                $this.attr("readonly","readonly");
                if($this.attr("type")=="file"){
                    $this.prop("disabled",true);
                }
                $(".btn-change-video").hide();
            }else{
                $this.removeAttr("readonly");
                if($this.attr("type")=="file"){
                    $this.prop("disabled",false);
                }
                $(".btn-change-pic").show();
            }
        });
    }
    //获取课程状态
    function getStatus(){
        _status = ($("#status").val()||"false")=="true"?true:false;
        getPageFlag();
        return _status;
    }
    //获取页面标识符_pageFlag的值
    function getPageFlag(){
        if(($("#id").val()+"")){
            _pageFlag = _status?"query":"update";
        }else{
            _pageFlag = "add";
        }
        return _pageFlag;
    }



    //新增课程
    function addItem(){
        submitCourseInfo({"flag":"add"});
    }
    //修改课程
    function updateItem(){
        submitCourseInfo({"flag":"update"});
    }
    //下架课程
    function updateDownItem(){
        updateCourse({"status":false,"id":_courseId});
    }
    //删除课程
    function delItem(){
        if(_status) return false;
        delCourseOrChapter({"type":"course"});
    }



    //ajax查询课程内容
    function loadCourse(){
        _loadingIndex = _helper.fridayLoadinFun(_errorTips["P008"]);
        setTimeout(function(){
            $.ajax({
                type: "GET",
                url:ajaxUrl[environment].queryCourse + _courseId,
                dataType: "json"
            }).done(function(data) {
                if(data && data.code==200){
                    _courseData = data.data;
                    loadChapter();
                    //setCourseForm();
                    //btnInit();
                }else{
                    _helper.ajaxMessage({"message":(data&&data.message)||"加载失败！","callback":btnInit});
                }
            }).fail(function(){
                _helper.ajaxErrorTips({"tips":"加载失败，请稍后再试！","callback":btnInit});
            }).always(function(){
                //layer.close(_loadingIndex);
            });
        },ajaxUrl[environment].settimeoutTime);
    }
    //ajax新增或修改课程信息
    function submitCourseInfo(obj){
        if(!obj) obj={};
        if(!obj.flag) obj.flag="add";
        var $detailForm = $("#detailForm");
        if(!JudgmentNull($detailForm.find("input[name='title']"),_errorTips["P001"])) return false;
        if(!JudgmentNull($detailForm.find("input[name='course_time']"),_errorTips["P002"])) return false;
        if(!JudgmentNull($detailForm.find("textarea[name='description']"),_errorTips["P004"])) return false;
        if(!JudgmentNull($detailForm.find("input[name='cover_id']"),_errorTips["P004"])) return false;

        _loadingIndex = _helper.fridayLoadinFun(_errorTips["P007"]);
        var formData=new FormData($("#detailForm")[0]);
        var tips = obj.flag=="add"?"新增":"修改";
        var url = obj.flag=="add"?ajaxUrl[environment].addCourse:ajaxUrl[environment].updateCourse+_courseId;
        var type= obj.flag=="add"?"POST":"PUT";
        setTimeout(function(){
            $.ajax({
                type: type,
                url:url,
                cache: false,
                data: formData,
                contentType: false,
                processData: false,
                dataType:"json"
            }).done(function(data) {
                if(data && data.code==200){
                    _courseData = data.data;
                    setCourseForm();
                    _helper.ajaxMessage({"message":tips+"成功！","callback":btnInit});
                }else{
                    _helper.ajaxMessage({"message":(data&&data.message)||tips+"失败！","callback":btnInit});
                    if(obj.errorFun && typeof obj.errorFun == "function") obj.errorFun();
                }
            }).fail(function(){
                _helper.ajaxErrorTips({"tips":tips+"失败，请稍后再试！","callback":btnInit});
                if(obj.errorFun && typeof obj.errorFun == "function") obj.errorFun();
            }).always(function(){
                layer.close(_loadingIndex);
            });
        },ajaxUrl[environment].settimeoutTime);
    }
    //下架课程
    function updateCourse(obj){
        if(!obj) obj={};
        var tips="确定要下架吗？";
        if(obj.status){
            tips="确定要上架吗？";
        }
        layer.confirm(tips, {icon: 3, title:'修改提示',offset: 't'}, function(index){
            layer.close(index);
            _loadingIndex = _helper.fridayLoadinFun();
            setTimeout(function(){
                $.ajax({
                    type: "PUT",
                    url:ajaxUrl[environment].updateCourse+obj.id+"/status",
                    dataType: "json"
                }).done(function(data) {
                    if(data && data.code==200){
                        _helper.ajaxMessage({"message":"修改成功！","callback":function(){}});
                        _courseData.status = obj.status;
                        setCourseForm();
                        btnInit();
                    }else{
                        _helper.ajaxMessage({"message":(data&&data.message)||"修改失败！"});
                    }
                }).fail(function(){
                    _helper.ajaxErrorTips({"tips":"修改失败，请稍后再试！"});
                }).always(function(){
                    layer.close(_loadingIndex);
                });
            },ajaxUrl[environment].settimeoutTime);
        });
    }
    //ajax删除课程 或者删除章节
    function delCourseOrChapter(obj){
        if(!obj) obj={};
        var typeTitle = "课程";
        var url = ajaxUrl[environment].delCourse + _courseId;
        if(obj.type=="chapter"){
            typeTitle = "章节";
            url = ajaxUrl[environment].delChapter + obj.id;
        }
        layer.confirm('确定要删除该'+typeTitle+'吗?', {icon: 3, title:'删除提示',offset: 't'}, function(index){
            layer.close(index);
            _loadingIndex = _helper.fridayLoadinFun(_errorTips["P007"]);
            setTimeout(function(){
                $.ajax({
                    type: "DELETE",
                    url:url,
                    contentType: 'application/json',
                    dataType: "json"
                }).done(function(data) {
                    if(data && data.code==200){
                        if(obj.type=="course"){
                            _courseData={};
                            setCourseForm();
                        }else if(obj.type=="chapter"){
                            _courseData.chapterList.splice(_currentChapterIndex,1);
                            setChapterList(_courseData.chapterList);
                        }
                        _helper.ajaxMessage({"message":"删除成功！","callback":btnInit});
                    }else{
                        _helper.ajaxMessage({"message":(data&&data.message)||"删除失败！","callback":btnInit});
                    }
                }).fail(function(){
                    _helper.ajaxErrorTips({"tips":"删除失败，请稍后再试！","callback":btnInit});
                }).always(function(){
                    layer.close(_loadingIndex);
                });
            },ajaxUrl[environment].settimeoutTime);
        });
    }
    //ajax查询章节
    function loadChapter(){
        //_loadingIndex = _helper.fridayLoadinFun(_errorTips["P008"]);
        setTimeout(function(){
            $.ajax({
                type: "GET",
                url:ajaxUrl[environment].queryChapter,
                data:{"course_id":_courseId},
                dataType: "json"
            }).done(function(data) {
                if(data && data.code==200){
                    _courseData.chapterList = data.dataList;
                    setCourseForm();
                    btnInit();
                }else{
                    _helper.ajaxMessage({"message":(data&&data.message)||"加载失败！","callback":btnInit});
                }
            }).fail(function(){
                _helper.ajaxErrorTips({"tips":"加载失败，请稍后再试！","callback":btnInit});
            }).always(function(){
                layer.close(_loadingIndex);
            });
        },ajaxUrl[environment].settimeoutTime);
    }
    //ajax新增或修改章节信息
    function submitChapterInfo(obj){
        if(!obj) obj={};
        if(!obj.flag) obj.flag="add";
        var $chapterForm = $("#chapterForm");
        if(!JudgmentNull($chapterForm.find("input[name='title']"),_errorTips["P005"])) return false;
        //if(!JudgmentNull($chapterForm.find("textarea[name='content']"),_errorTips["P006"])) return false;
        if($chapterForm.find("select[name='chaptertype']").val()=="video"){
            if(!JudgmentNull($chapterForm.find("input[name='media_id']"),_errorTips["P009"])) return false;
        }else{
            if(!JudgmentNull($chapterForm.find("input[name='audio_id']"),_errorTips["P010"])) return false;
            if(!JudgmentNull($chapterForm.find("input[name='img_id']"),_errorTips["P011"])) return false;
        }

        var formData=new FormData($("#chapterForm")[0]);

        _loadingIndex = _helper.fridayLoadinFun(_errorTips["P007"]);
        var tips = obj.flag=="add"?"新增":"修改";
        var url = obj.flag=="add"?ajaxUrl[environment].addChapter:ajaxUrl[environment].updateChapter+_currentChapterId;
        var type= obj.flag=="add"?"POST":"PUT";
        setTimeout(function(){
            $.ajax({
                type: type,
                url:url,
                contentType: false,
                processData: false,
                data: formData,
                dataType: "json"
            }).done(function(data) {
                if(data && data.code==200){
                    _helper.ajaxMessage({"message":tips+"成功！","callback":function(){
                        if(!_courseData.chapterList) _courseData.chapterList=[];
                        if(obj.flag=="add"){
                            _courseData.chapterList.push(data.data);
                        }else{
                            _courseData.chapterList[_currentChapterIndex] = data.data;
                        }
                        setChapterList(_courseData.chapterList);
                        $('#myModal').modal("hide");
                        btnInit();
                    }});
                }else{
                    _helper.ajaxMessage({"message":(data&&data.message)||tips+"失败！"});
                }
            }).fail(function(){
                _helper.ajaxErrorTips({"tips":tips+"失败，请稍后再试！"});
            }).always(function(){
                layer.close(_loadingIndex);
            });
        },ajaxUrl[environment].settimeoutTime);
    }



    //设置课程表单
    function setCourseForm(obj){
        if(!obj) obj=_courseData;
        var $detailForm = $("#detailForm");
        $detailForm.find("input[name='title']").val(obj.title||"");
        $detailForm.find("input[name='id']").val(obj.id||"");
        _courseId = obj.id;
        $detailForm.find("input[name='status']").val(obj.status||"false");
        _status = getStatus();
        $detailForm.find("input[name='course_time']").val(_helper.timeFormat(obj.course_time)||"");
        $detailForm.find("textarea[name='description']").val(obj.description||"");

        if(obj.exts){
            $detailForm.find("input[name='cover_id']").UploadControl({"event":(obj.exts.cover?"showFile":"showInput"),"url":obj.exts.cover});
            $detailForm.find("input[name='media_id']").UploadControl({"event":(obj.exts.media?"showFile":"showInput"),"url":obj.exts.media});
        }

        setChapterList(obj.chapterList);
        btnInit();
    }
    //设置章节列表
    function setChapterList(chapterList){
        var html='<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">';
        if(chapterList && chapterList.length>0){
            for(var a= 0,a1=chapterList.length;a<a1;a++){
                html+='<div class="panel panel-default">\
                                <div class="panel-heading" role="tab" id="heading'+a+'">\
                                <h4 class="panel-title">\
                                <a data-toggle="collapse" data-parent="#accordion" href="#collapse'+a+'" aria-expanded="true" aria-controls="collapseOne">'+chapterList[a].title+'</a>';
                if(!_status){
                    html+='<span class="glyphicon glyphicon-edit pull-right btn-edit-chapter"></span><span class="glyphicon glyphicon-remove pull-right btn-del-chapter"></span>';
                }else{
                    html+='<span class="glyphicon glyphicon-search pull-right btn-query-chapter"></span>';
                }
                html+='    <input type="hidden" name="chapterInfo" value="'+a+'">\
                                </h4>\
                                </div>\
                                <div id="collapse'+a+'" class="panel-collapse collapse" role="tabpanel" aria-labelledby="heading'+a+'">\
                                <div class="panel-body">';
                if(chapterList[a].chaptertype=="video"){
                    html+='<p>章节视频路径：'+(chapterList[a].media_id||"")+'</p>';
                }else{
                    html+='<p>章节音频路径：'+(chapterList[a].audio_id||"")+'</p>';
                    html+='<p>章节图片路径：'+(chapterList[a].img_id||"")+'</p>';
                }
                html+='</div></div></div>';
            }
        }else{
            if(_status){
                html+='<div class="panel panel-default">\
                            <div class="panel-heading" role="tab">\
                            <h4 class="panel-title">\
                            <a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#" aria-expanded="false">该课程没有章节</a>\
                            </h4>\
                            </div>\
                            </div>';
            }
        }
        if(!_status){
            html+='<div class="panel panel-default">\
                            <div class="panel-heading" role="tab">\
                            <h4 class="panel-title">\
                            <a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#" aria-expanded="false">新增章节</a>\
                            <span class="glyphicon glyphicon-plus pull-right btn-add-chapter"></span>\
                            </h4>\
                            </div>\
                            </div>';
        }
        html+='</div>';
        $("#chapter_list").html(html);
        $(".chapter_info").show();
    }
    //暂停页面上所有的多媒体
    function pauseVideo(){
        $("video,audio").each(function(){
            this.pause();
            this.load();
        });
    }
    //获取某一章节信息
    function getChapterInfo(thisP){
        thisP = thisP instanceof $ ? thisP : $(thisP);
        _currentChapterIndex = thisP.siblings("input").val()||0;
        if(!_courseData.chapterList) _courseData.chapterList=[];
        return _courseData.chapterList[_currentChapterIndex]||{};
    }
    //根据新增 修改 查看章节，设置模态框
    function setModal(obj){
        if(!obj) obj={};

        if(!obj.chapterInfo) obj.chapterInfo = {};
        setChapterForm(obj.chapterInfo);

        if(!obj.flag) obj.flag = "add";
        var labelH = "新增章节";
        if(obj.flag == "add"){
            $(".btn-add-chapter-modal").removeClass("update").addClass("add").html("新增").show();
        }else if(obj.flag == "update"){
            $(".btn-add-chapter-modal").removeClass("add").addClass("update").html("保存").show();
            labelH = "修改章节";
        }else if(obj.flag == "query"){
            $(".btn-add-chapter-modal").hide();
            labelH = "查看章节";
        }
        $("#myModalLabel").html(labelH);
        $('#myModal').modal("show");
    }
    //设置模态框中章节表单
    function setChapterForm(chapterInfo){
        if(!chapterInfo) chapterInfo={};
        var $chapterForm = $("#chapterForm");
        $chapterForm.find("input[name='title']").val(chapterInfo.title||"");
        $chapterForm.find("input[name='id']").val(chapterInfo.id);
        _currentChapterId = chapterInfo.id;
        $chapterForm.find("input[name='course_id']").val(chapterInfo.course_id||_courseId);
        $chapterForm.find("select[name='chaptertype']").val(chapterInfo.chaptertype||"audio");
        $chapterForm.find("input[name='img_id']").UploadControl({"event":(chapterInfo.img_id?"showFile":"showInput"),"url":chapterInfo.img_id});
        $chapterForm.find("input[name='audio_id']").UploadControl({"event":(chapterInfo.audio_id?"showFile":"showInput"),"url":chapterInfo.audio_id});
        $chapterForm.find("input[name='media_id']").UploadControl({"event":(chapterInfo.media_id?"showFile":"showInput"),"url":chapterInfo.media_id});
        if($chapterForm.find("select[name='chaptertype']").val()=="video"){
            $chapterForm.find(".chapter_audio").hide();
            $chapterForm.find(".chapter_video").show();
        }else{
            $chapterForm.find(".chapter_audio").show();
            $chapterForm.find(".chapter_video").hide();
        }

        $("#chapterForm .error-tips").hide();
    }


    //判断是否为空值，同时显示错误提示
    function JudgmentNull(thisP,tips){
        if(!thisP) return true;
        thisP = thisP instanceof $?thisP:$(thisP);

        var $thisParent = thisP.parents(".line-item");
        if(!(thisP.val()+"")){
            $thisParent.find(".limit-tips").hide();
            $thisParent.find(".error-tips").show().find(".text").html(tips||"不能为空");
            return false;
        }else{
            $thisParent.find(".error-tips").hide();
            $thisParent.find(".limit-tips").show();
        }
        return true;
    }
});